<template>
  <div>
    <Row :gutter="20">
      <Col span="8">
        <Card :bordered="false">
          <p slot="title">镜像仓库</p>
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
            <FormItem label="环境" prop="env">
              <Input v-model="formValidate.env" placeholder="Enter your repositories env"></Input>
            </FormItem>
            <FormItem label="地址" prop="registry">
              <Input v-model="formValidate.registry" placeholder="Enter your registry"></Input>
            </FormItem>
            <FormItem label="命名空间" prop="namespace">
              <Input v-model="formValidate.namespace" placeholder="Enter your namespace"></Input>
            </FormItem>
            <FormItem label="帐号" prop="username">
              <Input v-model="formValidate.username" placeholder="Enter your username"></Input>
            </FormItem>
            <FormItem label="密码" prop="password">
              <Input type="password" v-model="formValidate.password" placeholder="Enter your password"></Input>
            </FormItem>
            <FormItem label="备注" prop="label">
              <Input v-model="formValidate.label" placeholder="Enter your label"></Input>
            </FormItem>
            <FormItem>
              <Button type="info" @click="handleSubmit('formValidate')" style="margin-left: 12px">创建</Button>
              <Button type="warning" @click="handleReset('formValidate')" style="margin-left: 12px">取消</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
      <Col span="8">
        <Card :bordered="false">
          <p slot="title">ldap认证</p>
          <Form ref="ldapValidate" :model="ldapValidate" :label-width="80">
            <FormItem label="名称" prop="name">
              <Input v-model="ldapValidate.name" placeholder="Enter your ldap name"></Input>
            </FormItem>
            <FormItem label="服务器url" prop="url">
              <Input v-model="ldapValidate.url" placeholder="Enter your ldap server url"></Input>
            </FormItem>
            <FormItem label="服务器端口" prop="port">
              <Input v-model="ldapValidate.port" placeholder="Enter your ldap server port"></Input>
            </FormItem>
            <FormItem label="管理员DN" prop="dn">
              <Input v-model="ldapValidate.dn" placeholder="Enter your admin dn"></Input>
            </FormItem>
            <FormItem label="管理员密码" prop="password">
              <Input type="password" v-model="ldapValidate.password" placeholder="Enter your admin password"></Input>
            </FormItem>
            <FormItem label="Search_Filter" prop="search_filter">
              <Input v-model="ldapValidate.search_filter" placeholder="Enter your search filter"></Input>
            </FormItem>
            <FormItem label="SCBASE" prop="ldap_scbase">
              <Input v-model="ldapValidate.ldap_scbase" placeholder="Enter your LDAP SCBASE"></Input>
            </FormItem>
            <FormItem>
              <Button type="info" @click="ldapSubmit('ldapValidate')">保存</Button>
              <Button type="success" @click="ldapConnectTest('ldapValidate')" style="margin-left: 12px">连接测试</Button>
              <Button type="error" @click="ldapReset('ldapValidate')" style="margin-left: 12px">一键清空</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
      <Col span="8">
        <Card :bordered="false">
          <p slot="title">钉钉机器人</p>
          <Form ref="robotValidate" :model="robotValidate" :label-width="80">
            <FormItem label="机器人名称" prop="robot_name">
              <!-- <Select v-model="robotValidate.robot_name" placeholder="Select your work type">
                <Option value="work_order">工单机器人</Option>
                <Option value="deploy">发布机器人</Option>
              </Select> -->
              <Input v-model="robotValidate.robot_name" placeholder="Enter your robot name"></Input>
            </FormItem>
            <FormItem label="webhook" prop="webhook">
              <Input v-model="robotValidate.webhook" placeholder="Enter your webhook"></Input>
            </FormItem>
            <FormItem>
              <Button type="info" @click="robotSubmit('robotValidate')" style="margin-left: 12px">创建</Button>
              <Button type="warning" @click="robotReset('robotValidate')" style="margin-left: 12px">取消</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Row :gutter="20" style="margin-top: 10px;">
      <Col span="24">
        <Card :bordered="false">
          <p slot="title">仓库列表</p>
          <div style="padding-bottom: 20px;">
            <Table border :columns="columns1" :data="data1">
              <template slot-scope="{ row }" slot="name">
                <strong>{{ row.name }}</strong>
              </template>
              <template slot-scope="{ row, index }" slot="action">
                <Button type="success" size="small" style="margin-right: 5px" @click="handConnect(index)">测试</Button>
                <Button type="warning" size="small" style="margin-right: 5px" @click="updateRepo_id(index)">修改</Button>
                <Button type="error" size="small" @click="remove(index)">删除</Button>
              </template>
            </Table>
          </div>
          <div v-if="repoCount>6" style="padding-bottom: 10px;">
            <Page :total="repoCount" size="small" :page-size="6" current.sync="current" @on-change="RepoSwitchPage" />
          </div>
          <Modal v-model="modal1" draggable scrollable title="修改仓库" @on-ok="updateRepo_info">
            <Form ref="formValidate2" :model="formValidate2" :label-width="65">
              <FormItem label="环境" prop="env">
                <Input v-model="formValidate2.env" placeholder="Enter your repositories env"></Input>
              </FormItem>
              <FormItem label="地址" prop="registry">
                <Input v-model="formValidate2.registry" placeholder="Enter your registry"></Input>
              </FormItem>
              <FormItem label="命名空间" prop="namespace">
                <Input v-model="formValidate2.namespace" placeholder="Enter your namespace"></Input>
              </FormItem>
              <FormItem label="帐号" prop="username">
                <Input v-model="formValidate2.username" placeholder="Enter your username"></Input>
              </FormItem>
              <FormItem label="密码" prop="password">
                <Input type="password" v-model="formValidate2.password" placeholder="Enter your password"></Input>
              </FormItem>
              <FormItem label="备注" prop="label">
                <Input v-model="formValidate2.label" placeholder="Enter your label"></Input>
              </FormItem>
            </Form>
          </Modal>
        </Card>
      </Col>
      <Col span="24">
        <Card :bordered="false">
          <p slot="title">机器人列表</p>
          <Table border :columns="Robotcolumns" :data="robot_data">
            <template slot-scope="{ row, index }" slot="action">
              <Button type="success" size="small" @click="robotConnect(index)" style="margin-right: 5px">测试</Button>
              <Button type="warning" size="small" style="margin-right: 5px" @click="updateRobot_id(index)">修改</Button>
              <Button type="error" size="small" @click="robotRemove(index)">删除</Button>
            </template>
          </Table>
          <Modal v-model="robot_modal" draggable scrollable title="修改机器人信息" @on-ok="updateRobot_info">
            <Form ref="robotValidate_update" :model="robotValidate_update" :label-width="80">
            <FormItem label="名称" prop="robot_name">
              <!-- <Select v-model="robotValidate_update.robot_name" placeholder="Select your work type">
                <Option value="work_order">工单机器人</Option>
                <Option value="deploy">发布机器人</Option>
              </Select> -->
              <Input v-model="robotValidate_update.robot_name" placeholder="Enter your robot name"></Input>
            </FormItem>
            <FormItem label="webhook" prop="webhook">
              <Input v-model="robotValidate_update.webhook" placeholder="Enter your webhook"></Input>
            </FormItem>
          </Form>
          </Modal>
        </Card>
      </col>
    </Row>
  </div>
</template>

<script>
import { robotDelete, robotTest, robotUpdate } from '@/api/sysconfig'
import { ldapUserAuthGroup, ldapUserAuthGroupGet } from '@/api/sysconfig'
import { addRepo, repoList, connectStatus, ldapConnectTest } from '@/api/sysconfig'
import { deleteRepo, updateRepo, robotList, robotCreate } from '@/api/sysconfig'

  export default {
    data () {
      return {
        repoPage: 1,
        repoPageSize: 6,
        repoCount: null,
        modal1: false,
        robot_modal: false,
        robot_id: null,
        columns_id: null,
        formValidate: {
          env: '',
          registry: '',
          namespace: '',
          username: '',
          password: '',
          label: ''
        },
        formValidate2: {
          env: '',
          registry: '',
          namespace: '',
          username: '',
          password: '',
          label: ''
        },
        ruleValidate: {
          env: [
            { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ],
          registry: [
            { required: true, message: 'The registry cannot be empty', trigger: 'blur' }
          ],
          namespace: [
            { required: true, message: 'The namespace cannot be empty', trigger: 'blur' }
          ],
          username: [
            { required: true, message: 'The username cannot be empty', trigger: 'blur' }
          ],
          password: [
            { required: true, message: 'The password cannot be empty', trigger: 'blur' }
          ]
        },
        columns1: [
          {
            title: '环境',
            key: 'env'
          },
          {
            title: '地址',
            key: 'registry'
          },
          {
            title: '命名空间',
            key: 'namespace'
          },
          {
            title: '帐号',
            key: 'username'
          },
          {
            title: '备注',
            key: 'label'
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '更新日期',
            key: 'update_time'
          },
          {
            title: '操作',
            slot: 'action',
            width: 170,
            align: 'center'
          }
        ],
        data1: [],
        robot_data: [],
        robotValidate: {
          robot_name: '',
          webhook: ''
        },
        ldapValidate: {
          name: '',
          url: '',
          port: '389',
          dn: '',
          password: '',
          search_filter: '',
          ldap_scbase: ''
        },
        robotValidate_update: {
          robot_name: '',
          webhook: ''
        },
        Robotcolumns: [
          {
            title: '名称',
            key: 'robot_name',
            width: '200px'
          },
          {
            title: 'webhook',
            key: 'webhook'
          },
          {
            title: '操作',
            slot: 'action',
            width: 220,
            align: 'center'
          }
        ]
      }
    },
    created () {
      this.data_list();
      this.GetLdapInfo();
      this.robot_data_list();
    },
    methods: {
      // 获取缓存数据
      data_list () {
        var params = {
          'Page': this.repoPage,
          'PageSize': this.repoPageSize
        }
        repoList(params).then(res => {
          this.repoCount = res.data.count
          this.data1 = res.data.results
        }).catch(err => {
          this.$Message.error({content:'接口请求失败!',duration: 5,closable: true})
        });
      },
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求后端接口创建数据
            addRepo(this.formValidate).then(res => {
              this.data_list()  //在创建新地址时再次请求数据
              this.$Message.success({content:'创建成功!',duration: 5,closable: true});
            }).catch( err => {
              this.$Message.error({content:'创建失败!',duration: 5,closable: true})
            })
          }
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      // 测试连接状态
      handConnect (index) {
        connectStatus(this.data1[index].id).then(res => {
          this.$Message.success({content:'连接成功!',duration: 2,closable: true})
        }).catch( err => {
          this.$Message.error({content:'无法连接!',duration: 2,closable: true})
        })
      },
      RepoSwitchPage (page) {
        this.repoPage = page;
        this.data_list()
      },
      // 获取id
      updateRepo_id (index) {
        this.modal1 = true
        this.columns_id = this.data1[index].id
      },
      // 更新仓库信息
      updateRepo_info() {
        // console.log(this.columns_id,this.formValidate2)
        var data = {};
        for (const key in this.formValidate2) {
          if (this.formValidate2[key] != 0) {
            data[key] = this.formValidate2[key]
          }
        }
        // 请求后端的patch接口
        updateRepo(this.columns_id, data).then(res => {
          this.$Message.success({content:'修改成功!',duration: 5,closable: true})
          this.data_list()
        }).catch(err => {
          this.$Message.error({content:'修改失败!',duration: 5,closable: true})
        })
      },
      // 删除
      remove (index) {
        deleteRepo(this.data1[index].id).then(res => {
          this.data1.splice(index, 1);
          this.repoPage = 1;
          this.$Message.success({content:'删除成功!',duration: 5,closable: true})
        }).catch(err => {
          this.$Message.error({content:'删除失败!',duration: 5,closable: true})
        })
      },
      //获取机器人信息
      robot_data_list () {
        robotList().then(res => {
          this.robot_data = res.data
        })
      },
      // 测试ldap连接
      ldapConnectTest(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            ldapConnectTest(this.ldapValidate).then(res => {
              if (res.data.status === 'success') {
                this.$Message.success("连接成功!")
              } else {
                this.$message.error("连接失败!")
              }
            }).catch(err => {
              console.log(err)
              this.$Message.error("服务器内部错误!")
            })
            .catch(err => {
              console.log(err)
            })
          }
        })
      },
      // 获取ldap管理设置信息
      GetLdapInfo() {
        ldapUserAuthGroupGet().then(res => {
          for (const key in res.data) {
            this.ldapValidate.name = res.data[key].name;
            this.ldapValidate.url = res.data[key].host;
            this.ldapValidate.dn = res.data[key].admin_dn
            this.ldapValidate.password = res.data[key].admin_password
            this.ldapValidate.port = res.data[key].port
            this.ldapValidate.search_filter = res.data[key].search_filter
            this.ldapValidate.ldap_scbase = res.data[key].scbase
          }
        })
      },
      // 更新ldap信息
      ldapSubmit(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求ldap更新数据接口
            ldapUserAuthGroup(1, this.ldapValidate).then(res => {
              this.$Message.success("更新成功")
            })
          }
        })
      },
      ldapReset (name) {
        this.$refs[name].resetFields()
      },
      //测试机器人
      robotConnect (index) {
        robotTest(this.robot_data[index].id).then(res => {
          this.$Message.success("测试成功!")
        }).catch(err => {
          this.$Message.error("测试失败!")
        })
      },
      //创建机器人
      robotSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求后端接口创建数据
            robotCreate(this.robotValidate).then(res => {
              this.robot_data_list()
              this.$Message.success("机器人创建成功!")
            }).catch(err => {
              this.$Message.error("接口请求失败!")
            })
          }
        })
      },
      //清空机器人表单
      robotReset (name) {
        this.$refs[name].resetFields();
      },
      // 删除机器人
      robotRemove (index) {
        robotDelete(this.robot_data[index].id).then(res => {
          this.robot_data.splice(index, 1);
          this.$Message.success("删除成功!")
        }).catch(err => {
          this.$Message.error("删除失败!")
        })
      },
      //更新机器人
      updateRobot_id (index) {
        this.robot_modal = true;
        this.$refs['robotValidate_update'].resetFields();
        this.robot_id = this.robot_data[index].id
      },
      //更新机器人
      updateRobot_info () {
        var data = {};
        for (const key in this.robotValidate_update) {
          if (this.robotValidate_update[key] != 0) {
            data[key] = this.robotValidate_update[key]
          }
        }
        // 请求后端的patch接口
        robotUpdate(this.robot_id, data).then(res => {
          this.robot_data_list()
          this.$Message.success("修改成功!")
        }).catch(err => {
          this.$Message.error("修改失败!")
        })
      }
    }
  }
</script>